package com.fqgj.xjd.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.MD5;
import com.fqgj.xjd.user.client.enums.CreditAuthTypeEnum;
import com.fqgj.xjd.user.client.enums.UserBindCardTypeEnum;
import com.fqgj.xjd.user.client.request.BankAuth;
import com.fqgj.xjd.user.client.request.CreditAuthRequest;
import com.fqgj.xjd.user.client.request.Mobile;
import com.fqgj.xjd.user.client.request.ZmCredit;
import com.fqgj.xjd.user.client.response.CreditAuthResponse;
import com.fqgj.xjd.user.dao.*;
import com.fqgj.xjd.user.entity.*;
import com.fqgj.xjd.user.service.UserAuthCreditService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2017/2/27
 * Time: 下午2:24
 * 用户实名认证服务
 */
@Service
public class UserAuthCreditServiceImpl implements UserAuthCreditService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserAuthCreditServiceImpl.class);

    private static final int PAGE_SIZE = 1000;
    @Autowired
    private UserAuthCreditDao userAuthCreditDao;

    @Autowired
    private UserAuthZhimaDao userAuthZhimaDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserAccessDao userAccessDao;

    @Autowired
    private UserAuthBankDao userAuthBankDao;

    @Override   
    public Boolean cancelAuth(CreditAuthRequest creditAuth) {
        if (CreditAuthTypeEnum.ZM.getType().equals(creditAuth.getAuthType())) {
            userAuthZhimaDao.deleteByUserCode(creditAuth.getUserCode());
        }

        UserAuthCreditEntity userAuthCreditEntity = userAuthCreditDao.selectUserAuthCreditByUserCode(creditAuth.getUserCode());
        if (userAuthCreditEntity != null) {
            userAuthCreditEntity.setIsAuthorized(0);
            userAuthCreditEntity.setAuthType(creditAuth.getAuthType());
            userAuthCreditDao.updateByPrimaryKey(userAuthCreditEntity);
        }

        return true;
    }
    @Override
    public Boolean bankAuth(CreditAuthRequest creditAuth) {

        UserAuthCreditEntity userAuthCreditEntity = userAuthCreditDao.selectUserAuthCreditByUserCode(creditAuth.getUserCode());
        LOGGER.info("==芝麻授信==,userCode:{},userAuthCreditEntity:{}", creditAuth.getUserCode(), userAuthCreditEntity == null);
        if (userAuthCreditEntity == null) {//初始化
            userAuthCreditEntity = new UserAuthCreditEntity();
            userAuthCreditEntity.setUserCode(creditAuth.getUserCode());
            userAuthCreditEntity.setIsAuthorized(1);
            userAuthCreditEntity.setAuthType(creditAuth.getAuthType());
            userAuthCreditDao.insert(userAuthCreditEntity);
        }
        if (creditAuth.getAuthorized()) {
            UserEntity userEntity = userDao.selectByIdentityNo(creditAuth.getBankAuth().getIdentityCardId());
            LOGGER.info("==芝麻授信==,UserEntity:{}", userEntity == null);
            UserAccessEntity userAccessEntity = userAccessDao.selectUserAccessByUserCode(creditAuth.getUserCode());
            LOGGER.info("==芝麻授信==,userCode:{}", userAccessEntity == null ? 0 : 1);
            if (userAccessEntity == null) {
                return false;
            }

            String customerCode = null;
            if (userEntity == null) {
                LOGGER.info("==芝麻授信,插入新数据==,userCode:{}");
                //todo 当customerCode需要单独生成时，修改此处
                UserEntity customer = new UserEntity();
                customerCode = creditAuth.getUserCode();
                customer.setCustomerCode(customerCode);
                customer.setUserCode(creditAuth.getUserCode());
                customer.setName(creditAuth.getBankAuth().getUsername());
                customer.setIdentityNo(creditAuth.getBankAuth().getIdentityCardId());
                customer.setMobile(userAccessEntity.getMobile());
                customer.setMd5Mobile(MD5.md5(userAccessEntity.getMobile()));
                customer.setMd5MobileIdentityNo(MD5.md5(userAccessEntity.getMobile() + customer.getIdentityNo()));
                userDao.insert(customer);
            } else {
                customerCode = userEntity.getCustomerCode();
            }
            userAccessDao.updateCustomerCodeByUserCode(creditAuth.getUserCode(), customerCode);
        }
        return true;
    }

    @Override
    public Boolean auth(CreditAuthRequest creditAuth) {
            LOGGER.info("==芝麻授信==,userCode:" + JSON.toJSONString(creditAuth));
            //细节
            if (CreditAuthTypeEnum.ZM.getType().equals(creditAuth.getAuthType())) {
                zmDetail(creditAuth.getZmCredit(), creditAuth.getAuthorized());
            }
            UserAuthCreditEntity userAuthCreditEntity = userAuthCreditDao.selectUserAuthCreditByUserCode(creditAuth.getUserCode());
            LOGGER.info("==芝麻授信==,userCode:{},userAuthCreditEntity:{}", creditAuth.getUserCode(), userAuthCreditEntity == null);
            if (userAuthCreditEntity == null) {//初始化
                userAuthCreditEntity = new UserAuthCreditEntity();
                userAuthCreditEntity.setUserCode(creditAuth.getUserCode());
                userAuthCreditEntity.setIsAuthorized(0);
                userAuthCreditEntity.setAuthType(creditAuth.getAuthType());
                userAuthCreditDao.insert(userAuthCreditEntity);
                return true;
            }
            userAuthCreditEntity.setIsAuthorized(creditAuth.getAuthorized() ? 1 : 0);
            if (!userAuthCreditEntity.getAuthType().equals(creditAuth.getAuthType())) {
                userAuthCreditEntity.setAuthType(creditAuth.getAuthType());
            }
            String name = null;
            String identity_no = null;
            if(null != creditAuth.getZmCredit()){
                name = creditAuth.getZmCredit().getUserName();
                identity_no= creditAuth.getZmCredit().getIdentityNo();
            }else{
                name = creditAuth.getBankAuth().getUsername();
                identity_no= creditAuth.getBankAuth().getIdentityCardId();
            }
            if (creditAuth.getAuthorized()) {
                UserEntity userEntity = userDao.selectByIdentityNo(identity_no);
                LOGGER.info("==芝麻授信==,UserEntity:{}", userEntity == null);
                UserAccessEntity userAccessEntity = userAccessDao.selectUserAccessByUserCode(creditAuth.getUserCode());
                LOGGER.info("==芝麻授信==,userCode:{}", userAccessEntity == null ? 0 : 1);
                if (userAccessEntity == null) {
                    return false;
                }
                String customerCode = null;
                if (userEntity == null) {
                    //todo 当customerCode需要单独生成时，修改此处
                    UserEntity customer = new UserEntity();
                    customerCode = creditAuth.getUserCode();
                    customer.setCustomerCode(customerCode);
                    customer.setUserCode(creditAuth.getUserCode());
                    customer.setName(name);
                    customer.setIdentityNo(identity_no);
                    customer.setMobile(userAccessEntity.getMobile());
                    customer.setMd5Mobile(MD5.md5(userAccessEntity.getMobile()));
                    customer.setMd5MobileIdentityNo(MD5.md5(userAccessEntity.getMobile() + identity_no));
                    userDao.insert(customer);
                } else {
                    customerCode = userEntity.getCustomerCode();
                }
                userAccessDao.updateCustomerCodeByUserCode(creditAuth.getUserCode(), customerCode);
            }
            userAuthCreditDao.updateByPrimaryKey(userAuthCreditEntity);

        return true;
    }

    @Override
    public CreditAuthResponse getCreditAuthInfoByUserCode(String userCode) {
        UserAuthCreditEntity userAuthCreditEntity = userAuthCreditDao.selectUserAuthCreditByUserCode(userCode);
        if (userAuthCreditEntity == null) {
            return null;
        }

        ZmCredit zmCredit = null;
        UserAuthZhimaEntity zmCreditEntity = userAuthZhimaDao.selectUserAuthZhimaByUserCode(userCode);
        if (zmCreditEntity != null) {
            zmCredit = new ZmCredit(userCode,zmCreditEntity.getOpenId(), zmCreditEntity.getName(), zmCreditEntity.getIdentityNo(),zmCreditEntity.getScore());
            zmCredit.setOpenId(zmCreditEntity.getOpenId());
        }
        BankAuth bankAuth = null;
        UserAuthBankEntity userAuthBankEntity = userAuthBankDao.selectUserBankByUserCode(userCode);
        UserAccessEntity userAccessEntity = userAccessDao.selectUserAccessByUserCode(userCode);
        UserEntity userEntity = userDao.selectByCustomerCode(userAccessEntity.getCustomerCode());
        if (userAuthBankEntity != null) {
            bankAuth = new BankAuth();

            if (UserBindCardTypeEnum.CARD_51.getCode().equals(userAuthBankEntity.getType())) {
                bankAuth.setBankProviderEnum(UserBindCardTypeEnum.CARD_51);
            } else if (UserBindCardTypeEnum.CARD_LL.getCode().equals(userAuthBankEntity.getType())) {
                bankAuth.setBankProviderEnum(UserBindCardTypeEnum.CARD_LL);
            }
            if (userAuthBankEntity.getStatus() != 0) {
                bankAuth.setBindSuccess(true);
            }
            else bankAuth.setBindSuccess(false);

            bankAuth.setUsername(userEntity.getName());
            bankAuth.setIdentityCardId(userEntity.getIdentityNo());
            bankAuth.setCode(userAuthBankEntity.getCode());
            bankAuth.setMobile(new Mobile().setMobile(userAuthBankEntity.getMobile()));
            bankAuth.setName(userAuthBankEntity.getName());
            bankAuth.setNumber(userAuthBankEntity.getCardNo());
            bankAuth.setUserCode(userAuthBankEntity.getUserCode());
        }

        CreditAuthResponse response = new CreditAuthResponse();
        response.setAuthorized(userAuthCreditEntity.getIsAuthorized() == 0 ? false : true);
        response.setAuthType(CreditAuthTypeEnum.getEnumByType(userAuthCreditEntity.getAuthType()).getType());
        response.setBankAuth(bankAuth);
        response.setUserCode(userCode);
        response.setZmCredit(zmCredit);
        return response;
    }

    /**
     *
     */
    private void bankDetail(BankAuth bankAuth, Boolean success) {
        UserAuthBankEntity entity = userAuthBankDao.selectUserBankByUserCode(bankAuth.getUserCode());
        if(null == entity){
            LOGGER.info("user_auth_bank表中不存在该用户记录，无法修改状态");
            return;
        }
        UserAuthBankEntity entity1 = new UserAuthBankEntity();
        entity1.setId(entity.getId());
        entity1.setStatus(1);
        if (!success) {
            entity1.setStatus(0);
        }
        userAuthBankDao.updateByPrimaryKey(entity1);

    }
    /**
     * 处理芝麻实名的相关逻辑
     */
    private void zmDetail(ZmCredit zmCredit, Boolean success) {
        UserAuthZhimaEntity userZmCreditEntity = userAuthZhimaDao.selectUserAuthZhimaWithDeletedByUserCode(zmCredit.getUserCode());
        if(null == userZmCreditEntity){
            userZmCreditEntity = new UserAuthZhimaEntity();
        }
        userZmCreditEntity.setUserCode(zmCredit.getUserCode());
        userZmCreditEntity.setIdentityNo(StringUtils.trimToEmpty(zmCredit.getIdentityNo()));
        userZmCreditEntity.setName(StringUtils.trimToEmpty(zmCredit.getUserName()));
        userZmCreditEntity.setOpenId(zmCredit.getOpenId());
//        if(null != zmCredit.getOpenId()){
//            ZmxyCreditResult result = riskIntegrationService.queryUserZmInfo(zmCredit.getOpenId());
//            if(null != result && null != result.getZmScore()){
//                userZmCreditEntity.setScore(result.getZmScore().toString());
//            }
//        }

        userZmCreditEntity.setStatus(1);
        if (!success) {
            userZmCreditEntity.setStatus(0);
        }
        if(null == userZmCreditEntity.getId()){
            userAuthZhimaDao.insert(userZmCreditEntity);
        }else{
            userZmCreditEntity.setDeleted(false);
            userAuthZhimaDao.updateByPrimaryKey(userZmCreditEntity);
        }

    }
    @Override
    public void initZmScore(){
        Integer start = 0;
        int i = 0;
        LOGGER.info("init zmScore job start...");
        while (true){
            List<UserAuthZhimaEntity> userAuthZhimaEntities = userAuthZhimaDao.selectUserAuthZhimaListByPage(start,PAGE_SIZE);
//            for(UserAuthZhimaEntity entity:userAuthZhimaEntities){
//                if(null != entity.getOpenId()){
//                    ZmxyCreditResult result = riskIntegrationService.queryUserZmInfo(entity.getOpenId());
//                    if(null != result && null != result.getZmScore()){
//                        entity.setScore(result.getZmScore().toString());
//                        userAuthZhimaDao.updateByPrimaryKey(entity);
//
//                    }
//                }
//            }
            if(CollectionUtils.isEmpty(userAuthZhimaEntities)
                    ||userAuthZhimaEntities.size()<PAGE_SIZE){
                break;
            }
            start = (++i)*PAGE_SIZE;
        }
        LOGGER.info("init zmScore job end...");
    }

    @Override
    public void initUserNameAndIdentity(String userCode, String username, String identityNo) {
        UserEntity entity = userDao.selectByUserCode(userCode);
        if (entity == null) { //如果已存在usercode，则进行更新，否则插入
            UserEntity entity1 = new UserEntity();
            entity1.setUserCode(userCode);
            entity1.setName(username);
            entity1.setIdentityNo(identityNo);
            entity1.setCustomerCode(userCode);

            entity1.setGmtCreate(new Date());
            entity1.setDeleted(true);
            entity1.setGmtModified(new Date());
            userDao.initInsert(entity1);
        } else if (entity != null && entity.getDeleted() == true){
            UserEntity entity1 = new UserEntity();
            entity1.setUserCode(userCode);
            entity1.setName(username);
            entity1.setIdentityNo(identityNo);
            entity1.setDeleted(true);
            entity1.setId(entity.getId());
            userDao.updateByPrimaryKey(entity1);
        }
    }

}